﻿function PopupCenter(pageURL, title, w, h) {
  //debugger;
    var left = (screen.width / 2) - (w / 2);
    var top = (screen.height / 2) - (h / 2);
    var targetWin = window.open(pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
} 

//to get current date in dd/MM/yyyy format
function getCurrDate() {

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();

    if (dd < 10) { dd = '0' + dd };
    if (mm < 10) { mm = '0' + mm };
    today = mm + '/' + dd + '/' + yyyy;
    //today = dd + '/' + mm + '/' + yyyy; 
    return today;
}

//to get date in dd/MM/yyyy format
function getDate(opt) {
   
    var today = new Date();
    today.setDate(today.getDate() + opt);

    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!  
    var yyyy = today.getFullYear();

    if (dd < 10) { dd = '0' + dd };
    if (mm < 10) { mm = '0' + mm };
    today = mm + '/' + dd + '/' + yyyy;
    //today = dd + '/' + mm + '/' + yyyy; 
    return today;
}

//to get current date in yyyy,MM,dd format
function getCurrDateyyyyMMdd() {

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();

    if (dd < 10) { dd = '0' + dd };
    if (mm < 10) { mm = '0' + mm };

    today = yyyy + "," + mm + ',' + dd;
    //today = dd + '/' + mm + '/' + yyyy; 
    return today;

}

function numberOnly(ctrl) {
    ////debugger;   
    if (ctrl.value == "") {
        return true;
    }
    if (ctrl.value.match(/^\d+(\.\d+)?$/)) {
        return true;
    }
    else {
      
        alert("Please enter only numeric value !");
        ctrl.value = "";
    }
}

//validate date in MM/dd/yyyy format
function isValidDate(dateCtrl) {

    var date = dateCtrl.value;
    if (date != "") {
        var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
        if (matches == null) {
            alert("Please enter date in MM/dd/yyyy format !");
            dateCtrl.value = "";
            return false;
        }
    }

    return true;
}

function deleteAllCookies() {
    //check browser and do
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}


//validate date in MM/dd/yyyy format for jqgrid
function isValidDateGrid(dateCtrl) {
    ////debugger;
    var date = dateCtrl.value;
    if (date != "") {
        var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
        if (matches == null) {
            alert("Please enter date in MM/dd/yyyy format !");
            dateCtrl.value = "";
            return false;
        }
    }

    return true;
}


//to fill jqgird -common function
function fillgridCommon(result, tblname, pgname, gWidth, gHeight, editurll) {
    
    //debugger;
    var colD = result.datarow, colN = result.columns, colM = result.colModelList;

    jQuery(tblname).jqGrid({
        data: colD,
        datatype: 'local',
        gridview: true,
        colNames: colN,
        colModel: colM,
        caption: "Master Data",
        //url: "Callback.aspx?operation=get_Dimrows&table_name=" + table_name + "&dimname=" + dimname + "&hier_id=" + hier_id + "&node_id=" + node_id,
        //editurl: "MasterCallback.aspx?table_name=" + table_name + "&list_id=" + list_id,
        //editurl: "ConfigCallback.aspx?" + editurll,
        editurl: editurll,
        rowNum: 15,
        //pager: '#pager',
        pager: pgname,
        sortname: result.primarykey,
        sortorder: "desc",
        //        width: "200px",
        //        height: "200px",
        width: gWidth,
        height: gHeight,
        scrollOffset: 18,
        closeAfterEdit: true,
        ignoreCase: true,
        multiselect: true,
        viewrecords: true,
        loadComplete: function (data) {
            jQuery(tblname).hideCol(result.primarykey);
            if (gWidth == "200px") {
                jQuery(tblname).setGridWidth(620, true);
            }
            else {
                jQuery(tblname).setGridWidth("850", true);
            }
        },
        loadError: function (xhr, status, error) {
            alert('error');
        }
    });
}


////to fill jqgird -common function with Add , Edit and Delete
//function fillgridCommonNav(result, tblname, pgname, gWidth, gHeight, caption, editurll) {
//    ////debugger;
//    //alert($("#hidListCol").val());

//    var colD = result.datarow, colN = result.columns, colM = result.colModelList;

//    jQuery(tblname).jqGrid({
//        data: colD,
//        datatype: 'local',
//        //datatype: "json",
//        gridview: true,
//        colNames: colN,
//        colModel: colM,
//        caption: caption,
//        //editurl: editurll,
//        //editurl: "ConfigCallback.aspx?table=XMasterList",
//        editurl: "ConfigCallback.aspx?" + editurll,
//        // editurl: "ConfigCallback.aspx?table=XMasterListCol&list_id=" + jQuery("#dtXMasterList").jqGrid('getGridParam', 'selrow') +"&hidListCol=" + $("#hidListCol").val(),
//        rowNum: 10,
//        pager: pgname,
//        sortname: result.primarykey,
//        sortorder: "desc",
//        //width: "100%",
//        width: "800px",
//        height: "100%",
//        scrollOffset: 18,
//        closeAfterEdit: true,
//        ignoreCase: true,
//        // loadonce: true,
//        loadComplete: function (data) {
//            ////debugger;
//            jQuery(tblname).hideCol(result.primarykey);
//            jQuery(tblname).setGridWidth(980, true);
//        },
//        onSelectRow: function (rowid) {

//            if (tblname == "#dtXMasterList") {
//                var IsTableCreated = $(this).jqGrid('getCell', rowid, 'IsTableCreated');
//                if (IsTableCreated == "1") {
//                    //alert("Related Tables exists ! Can't Delete Table !");
//                    $("#del_" + this.id).addClass('ui-state-disabled');
//                }
//                else {
//                    $("#del_" + this.id).removeClass('ui-state-disabled');
//                }
//            }

//            if (tblname == "#dtXMasterListCol") {
//                ////debugger;
//                var tblrowid = jQuery("#dtXMasterList").jqGrid('getGridParam', 'selrow');
//                var IsTableCreated = jQuery("#dtXMasterList").jqGrid('getCell', tblrowid, 'IsTableCreated');
//                if (IsTableCreated == "1") {
//                    //alert("Related Tables exists ! Can't Delete Table !");
//                    $("#del_" + this.id).addClass('ui-state-disabled');
//                }
//                else {
//                    $("#del_" + this.id).removeClass('ui-state-disabled');
//                }
//            }

//            if (tblname == "#dtMUserType") {                
//                var hasUser = $(this).jqGrid('getCell', rowid, 'hasUser');
//                if (hasUser == "1") {
//                    //alert("Related Tables exists ! Can't Delete Table !");
//                    $("#del_" + this.id).addClass('ui-state-disabled');
//                }
//                else {
//                    $("#del_" + this.id).removeClass('ui-state-disabled');
//                }
//            }

//            return true;

//        },
//        loadError: function (xhr, status, error) {
//            ////debugger;
//            alert('error');
//        }
//    });

//    navGriddCommon(tblname, pgname);
//}

////to remove this after finding editurl
////to fill jqgird -common function with Add , Edit and Delete
//function fillgridCommonNavCol(result, tblname, pgname, gWidth, gHeight, caption, editurll) {
//    ////debugger;

//    //alert(editurll);
//    // alert("ConfigCallback.aspx?table=XMasterListCol&list_id=" + jQuery("#dtXMasterList").jqGrid('getGridParam', 'selrow') );
//    //alert($("#hidListCol").val());
//    var colD = result.datarow, colN = result.columns, colM = result.colModelList;

//    jQuery(tblname).jqGrid({
//        data: colD,
//        datatype: 'local',
//        gridview: true,
//        colNames: colN,
//        colModel: colM,
//        caption: caption,
//        //editurl: editurll,
//        //editurl: "ConfigCallback.aspx?table=XMasterList",
//        editurl: "ConfigCallback.aspx?table=XMasterListCol&list_id=" + jQuery("#dtXMasterList").jqGrid('getGridParam', 'selrow') + "&hidListCol=" + $("#hidListCol").val(),
//        rowNum: 10,
//        pager: pgname,
//        sortname: result.primarykey,
//        sortorder: "desc",
//        //width: "100%",
//        width: "800px",
//        height: "100%",
//        scrollOffset: 18,
//        closeAfterEdit: true,
//        ignoreCase: true,
//        loadComplete: function (data) {
//            // //debugger;
//            jQuery(tblname).hideCol(result.primarykey);
//            jQuery(tblname).setGridWidth(980, true);
//        },
//        loadError: function (xhr, status, error) {
//            ////debugger;
//            alert('error');
//        }
//    });
//    ////debugger;
//    navGriddCommon(tblname, pgname);
//    //jQuery("#dataGrid").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: true });
//}

function refreshgridCommon(result, tblname) {
    // ////debugger;
    var colD = result.datarow, colN = result.columns, colM = result.colModelList;
    //clear grid data
    $(tblname).jqGrid("clearGridData", true);

    //refresh jqgrid
    jQuery(tblname).jqGrid('setGridParam', { datatype: 'local', data: colD }).trigger("reloadGrid");
}


function afterSubCommon(response, postdata) {
    // //debugger;
    var arr = response.responseText.split("|");
    if (arr[0] == "false") {
        if (arr[1] != "") {
            return [false, arr[1]]
        }
        else {
            return [false, "some error in save !"]
        }
    }
    else {
        alert("saved successfully");
        return [true, "saved successfully !"]
    }

    //original 
    //    if (response.responseText == "true") {
    //        alert("saved successfully");
    //        return [true, "saved successfully !"]
    //    }
    //    else if (response.responseText == "false") {
    //        //alert("some error in save !");
    //        return [false, "some error in save !"]
    //    }
}

function navGriddCommon(tblname, pgname) {
    // //debugger;
    // alert("ll");

    jQuery(tblname).jqGrid('navGrid', pgname, { del: true, edit: true, add: true, search: true },
   {//edit

       afterSubmit: afterSubCommon,
       closeAfterEdit: true,
       reloadAfterSubmit: false,
       width: "500",
       modal: true,
       onInitializeForm: function (formid) {
           // //debugger;         
           //for  * sign for mandatory field  and datepicker
           colModelLocal = $(".ui-jqgrid-btable").get(0).p.colModel;
           var arr = tblname.split('#');
           colModelLocal = $("table[id=" + arr[1] + "]").get(0).p.colModel;
           var appendtag = "<font style='font-weight: bold; color: #FF0000; vertical-align: bottom;'>*</font>";

           for (i = 0, len = colModelLocal.length; i < len; i++) {
               var edtrul = colModelLocal[i].editrules;
               var name = colModelLocal[i].name;
               if (edtrul.date === true) {
                   $("#" + name, formid).datepicker();
               }
               if (edtrul.required === true) {
                   var relTo = $("#" + name, formid);
                   $(appendtag).insertAfter(relTo);
               }
           }

       },
       beforeShowForm: function (formid) {
           if (tblname == "#dtXMasterList") {
               ////debugger; // disasble
               // $('#tr_TABLE_ABBR', formid).hide();
               $('#TABLE_ABBR', formid).attr("disabled", "disabled");
               //color:#DDD9D9 for disable
           }

           ////debugger;
           if (tblname == "#dtXMasterListCol") {
               //put condition for if tables are created 
               var tblrowid = jQuery("#dtXMasterList").jqGrid('getGridParam', 'selrow');
               //var IsTableCreated = jQuery("#dtXMasterList").jqGrid('getCell', tblrowid, 'IsTableCreated');
               if (jQuery("#dtXMasterList").jqGrid('getCell', tblrowid, 'IsTableCreated') == "1") {
                   $('#FIELD_NAME', formid).attr("disabled", "disabled");
                   $('#DATA_TYPE', formid).attr("disabled", "disabled");

                   //IS_PRIMARY
                   $('#IS_PRIMARY', formid).attr("disabled", "disabled");
                   $('#CONTROL_TYPE', formid).attr("disabled", "disabled");

                   //IS_REQUIRED $('#checkBox').attr('checked');  
                   if ($('#IS_REQUIRED', formid).attr('checked')) //$('#IS_PRIMARY', formid).attr('checked')
                   {
                       //$('#IS_REQUIRED', formid).attr("disabled", "disabled");
                       //enable
                       if ($('#IS_PRIMARY', formid).attr('checked')) //$('#IS_PRIMARY', formid).attr('checked')
                       {
                           $('#IS_REQUIRED', formid).attr("disabled", "disabled");
                       }
                       else {
                           $('#IS_REQUIRED', formid).removeAttr("disabled");
                       }
                   }
                   else {

                       $('#IS_REQUIRED', formid).attr("disabled", "disabled");
                   }

                   if ($('#IS_PRIMARY', formid).attr('checked')) //$('#IS_PRIMARY', formid).attr('checked')
                   {
                       $('#IS_ACTIVE', formid).attr("disabled", "disabled");
                   }
                   else {
                       $('#IS_ACTIVE', formid).removeAttr("disabled");
                   }

               }
           }
       }
   },
    {//new
        // afterSubmit: afterSub,
        afterSubmit: function (response) {
            ////debugger;

            var arr = response.responseText.split("|");
            if (arr[0] == "false") {
                //if (response.responseText == "false") {               
                //alert(response.responseText);
                //alert(arr[1]);

                if (arr[1] != "") {
                    return [false, arr[1]]
                }
                else {
                    return [false, "some error in save !"]
                }
            }
            else {
                if (tblname == "#dtXMasterListCol") {
                    showhideCreateButoon($("#dtXMasterListCol").getGridParam("reccount") + 1);
                }
                return [true, "saved successfully !", response.responseText]
            }
        },
        closeAfterAdd: true,
        reloadAfterSubmit: false,
        width: "500",
        modal: true,
        onInitializeForm: function (formid) {
            ////debugger;
            //for  * sign for mandatory field  and datepicker
            colModelLocal = $(".ui-jqgrid-btable").get(0).p.colModel;
            var arr = tblname.split('#');
            colModelLocal = $("table[id=" + arr[1] + "]").get(0).p.colModel;
            var appendtag = "<font style='font-weight: bold; color: #FF0000; vertical-align: bottom;'>*</font>";

            for (i = 0, len = colModelLocal.length; i < len; i++) {
                var edtrul = colModelLocal[i].editrules;
                var name = colModelLocal[i].name;
                if (edtrul.date === true) {
                    $("#" + name, formid).datepicker();
                }
                if (edtrul.required === true) {
                    var relTo = $("#" + name, formid);
                    //alert(name);
                    //alert(relTo);
                    $(appendtag).insertAfter(relTo);
                }
            }
        },
        beforeShowForm: function (formid) {
            if (tblname == "#dtXMasterList") {
                $('#TABLE_ABBR', formid).removeAttr("disabled");
            }

            ////debugger;
            if (tblname == "#dtMUser") {
                $('#IS_ACTIVE', formid).attr('checked', 'checked');
            }

            //put condition for if tables are created 
            if (tblname == "#dtXMasterListCol") {
                var tblrowid = jQuery("#dtXMasterList").jqGrid('getGridParam', 'selrow');
                //var IsTableCreated = jQuery("#dtXMasterList").jqGrid('getCell', tblrowid, 'IsTableCreated');
                if (jQuery("#dtXMasterList").jqGrid('getCell', tblrowid, 'IsTableCreated') == "1") {

                    $('#FIELD_NAME', formid).removeAttr("disabled");
                    $('#DATA_TYPE', formid).removeAttr("disabled");
                    //new column should be by default active
                    $('#IS_ACTIVE', formid).attr('checked', 'checked');
                    $('#IS_REQUIRED', formid).attr("disabled", "disabled");
                    $('#IS_PRIMARY', formid).attr("disabled", "disabled");

                }
                else {

                    if ($('#IS_REQUIRED', formid).attr("disabled")) {
                        $('#IS_REQUIRED', formid).removeAttr("disabled");
                    }

                    if ($('#IS_PRIMARY', formid).attr("disabled")) {
                        $('#IS_PRIMARY', formid).removeAttr("disabled");
                    }

                    if ($('#CONTROL_TYPE', formid).attr("disabled")) {
                        $('#CONTROL_TYPE', formid).removeAttr("disabled");
                    }

                    if ($('#IS_ACTIVE', formid).attr("disabled")) {
                        $('#IS_ACTIVE', formid).removeAttr("disabled");
                    }
                }

            }
        }
    },
    {//delete
        afterSubmit: function (response) {
            ////debugger;
            if (response.responseText == "true") {
                if (tblname == "#dtXMasterListCol") {
                    showhideCreateButoon($("#dtXMasterListCol").getGridParam("reccount") - 1);
                }
                return [true, "deleted successfully !"]
            }
            else if (response.responseText == "false") {
                return [false, "some error in delete !"]
            }
            else {

                ////debugger;
                var arr = response.responseText.split(":");
                $("#hidListCol").val(arr[1]);
                //return [false, response.responseText]
                return [false, arr[1]]
            }
        },
        closeAfterEdit: true,
        reloadAfterSubmit: false,
        beforeShowForm: function (formid) {
            ////debugger;
            if (tblname == "#dtXMasterList") {
                list_id = jQuery("#dtXMasterList").jqGrid('getGridParam', 'selrow');
                //var IsTableCreated = jQuery("#dtXMasterList").getRowData(list_id)['IsTableCreated'];
                if (jQuery("#dtXMasterList").getRowData(list_id)['IsTableCreated'] == "1") {
                    alert("Related Tables exists ! Can't Delete Table !");
                    return false;
                }
            }
        }
    },
    {//complex search
        multipleSearch: true,
        multipleGroup: true,
        showQuery: true//,
        //, showRel: true,
        // odata: ['equal', 'not equal', 'less', 'less or equal', 'greater', 'greater or equal', 'begins with', 'does not begin with', 'is in', 'is not in', 'ends with', 'does not end with', 'contains', 'does not contain']
    }
);
}

////to change colprop on the fly
//if (ret.Mode == "Automatic")
//    jQuery("#table").setColProp('PRECISION', { required: false });
//else
//    jQuery("#table").setColProp('PRECISION', { required: true });


//suffice * if mandatory field and add datepicker on add/edit dialog box
function SufficeStar(colModelLocal, formid) {
    debugger;
    var appendtag = "<font style='font-weight: bold; color: #FF0000; vertical-align: bottom;'>*</font>";

    for (i = 0, len = colModelLocal.length; i < len; i++) {
        var edtrul = colModelLocal[i].editrules;
        var name = colModelLocal[i].name;
        if (edtrul.date === true) {
            $("#" + name, formid).datepicker();

            //if version grid
            var todate = getCurrDate();
            $("#" + name, formid).val(todate);
            //

        }
        if (edtrul.required === true) {            
            var relTo = $("#" + name, formid);
            $(appendtag).insertAfter(relTo);
        }
    }
}